package com.shxc.smarttrade.account.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.dialog.PhotoDialog;
import com.shxc.smarttrade.dialog.SexDialog;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.info.ContentsSwitch;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.GlideImageLoader;
import com.shxc.smarttrade.utils.GlideUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;
import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 编辑个人资料
 */
@ContentView(R.layout.activity_account_setting)
public class AccountSettingActivity extends BaseActivity implements TimePicker.OnTimeSelectListener {

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private final int PERMISSIONS_REQUEST_CAMERA = 9;

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;

    private List<String> path = new ArrayList<>();

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.head_imageview)
    ImageView head_imageview;
    @ViewInject(R.id.name_textview)
    TextView name_textview;
    @ViewInject(R.id.telephone_textview)
    TextView telephone_textview;
    @ViewInject(R.id.sex_textview)
    TextView sex_textview;
    @ViewInject(R.id.birthday_textview)
    TextView birthday_textview;
    @ViewInject(R.id.introduction_textview)
    TextView introduction_textview;

    private PhotoDialog photoDialog;
    private SexDialog sexDialog;

    private String headUrl;
    private String nick;
    private long sex;
    private int year;
    private int month;
    private int day;
    private String introduction;

    private GlideUtils glideUtils;

    private OSS oss;
    private boolean isUrlChanging = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        glideUtils = new GlideUtils(mContext);
        initMyDialog();
        initUi();
        initGallery();
        initOss();
        initTimepicker();
    }


    @Override
    protected void onResume() {
        super.onResume();
        setUi();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (photoDialog.isShowing()) {
            photoDialog.dismiss();
        }
        if (sexDialog.isShowing()) {
            sexDialog.dismiss();
        }
    }

    @Event({R.id.left_imageview, R.id.head_view, R.id.name_view, R.id.sex_view, R.id.birthday_view, R.id.introduction_view})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                //关闭
                finish();
                break;
            case R.id.head_view:
                //点击头像
                photoDialog.show();
                photoDialog.getPhoto_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions2();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getAlbum_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getCancel_texxtview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        photoDialog.dismiss();
                    }
                });

                break;
            case R.id.name_view:
                //点击昵称
                JumpTo(AccountNickActivity.class);
                break;
            case R.id.sex_view:
                //点击性别
                sexDialog.show();
                sexDialog.getMan_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sex = 0;
                        sexDialog.dismiss();
                        editUserInfo();
                    }
                });
                sexDialog.getWomen_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sex = 1;
                        sexDialog.dismiss();
                        editUserInfo();
                    }
                });
                sexDialog.getCancel_texxtview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sexDialog.dismiss();
                    }
                });

                break;
            case R.id.birthday_view:
                //点击设置生日
                mTimePicker.setSelectedDate(mDate.getTime());
                mTimePicker.show();
                break;
            case R.id.introduction_view:
                //点击简介
                JumpTo(AccountIntroductionActivity.class);
                break;
        }
    }

    private void initMyDialog() {
        photoDialog = new PhotoDialog(this,
                getResources().getIdentifier("BottomDialog", "style", getPackageName()));
        photoDialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.LEFT | Gravity.RIGHT);

        sexDialog = new SexDialog(this,
                getResources().getIdentifier("BottomDialog", "style", getPackageName()));
        sexDialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.LEFT | Gravity.RIGHT);
    }

    private void initUi() {
        if (title_textview == null) {
            Loger.e("null", "!");
        }
        title_textview.setText("编辑个人资料");
        left_imageview.setVisibility(View.VISIBLE);
        if (!AppUtils.isEmpty(spImp.getHeadUrl())) {
            glideUtils.showCircle(headUrl = spImp.getHeadUrl(), head_imageview);
        }
        name_textview.setText(nick = spImp.getNick());
        telephone_textview.setText(spImp.getEmail());
        Loger.e("sex", spImp.getSex());
        sex_textview.setText(spImp.getSex() == 0 ? "男" : "女");

        if (!AppUtils.isEmpty(spImp.getBirthday())) {
            String birthday = "";
            birthday = year + "年";
            if (month < 10) {
                birthday = birthday + "0";
            }
            birthday = birthday + month + "月";
            if (day < 10) {
                birthday = birthday + "0";
            }
            birthday = birthday + day + "日";
            birthday_textview.setText(birthday);
        }
        introduction_textview.setText(introduction = spImp.getIntroduction());

        if (!AppUtils.isEmpty(spImp.getBirthday())) {
            String[] ymd = spImp.getBirthday().split("-");
            year = Integer.parseInt(ymd[0]);
            month = Integer.parseInt(ymd[1]);
            day = Integer.parseInt(ymd[2]);
        } else {
            year = 1970;
            month = 1;
            day = 1;
        }
        Calendar cal = Calendar.getInstance();
        cal.set(year, month-1, day);
        mDate = cal.getTime();

        sex = spImp.getSex();
    }

    private TimePicker mTimePicker;
    private Date mDate;
    private int BLUE = Color.parseColor("#1f85fb");
    private int GRAY = Color.parseColor("#B3B3B3");

    private void initTimepicker() {

        final DefaultCenterDecoration decoration = new DefaultCenterDecoration(this);
        decoration.setLineColor(BLUE).setLineWidth(1);

        Calendar calendar = Calendar.getInstance();

        Calendar from = Calendar.getInstance();
        from.set(1970, 0, 1);


        int type = 0;
        type = type | TimePicker.TYPE_YEAR;
        type = type | TimePicker.TYPE_MONTH;
        type = type | TimePicker.TYPE_DAY;

        mTimePicker = new TimePicker.Builder(this, type, this)
                // 设置时间区间
                .setRangDate(from.getTimeInMillis(), calendar.getTimeInMillis())
                // 设置选中时间
                //.setSelectedDate()
                // 设置pickerview样式
                .setInterceptor(new BasePicker.Interceptor() {
                    @Override
                    public void intercept(PickerView pickerView) {
                        pickerView.setVisibleItemCount(3);
                        pickerView.setTextSize(15, 20);

                        pickerView.setColor(BLUE, GRAY);
                        // 设置CenterDecoration
                        pickerView.setCenterDecoration(decoration);

                        // 将年月设置为循环的
                        int type = (int) pickerView.getTag();
                        if (type == TimePicker.TYPE_YEAR || type == TimePicker.TYPE_MONTH) {
                            pickerView.setIsCirculation(true);
                        }
                    }
                })
                // 设置 Formatter
                .setFormatter(new TimePicker.DefaultFormatter() {
                    // 自定义Formatter显示去年，今年，明年
                    @Override
                    public CharSequence format(TimePicker picker, int type, int position, int num) {
                        if (type == TimePicker.TYPE_YEAR) {
//                            int offset = num - year;
//                            if (offset == -1) return "去年";
//                            if (offset == 0) return "今年";
//                            if (offset == 1) return "明年";
                            return num + "";
                        } else if (type == TimePicker.TYPE_MONTH) {
                            return num + "";
                        } else if (type == TimePicker.TYPE_DAY) {
                            return num + "";
                        }
                        return super.format(picker, type, position, num);
                    }
                }).create();

    }

    @Override
    public void onTimeSelect(TimePicker picker, Date date) {
        mDate = date;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);

        Loger.e("year", year);
        Loger.e("month", month);
        Loger.e("day", day);

        editUserInfo();
    }

    //初始化oss
    private void initOss() {
        // ACCESS_ID,ACCESS_KEY是在阿里云申请的
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Contents.ACCESSKEY_ID, Contents.ACCESSKEY_SECRET);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        // oss为全局变量，OSS_ENDPOINT是一个OSS区域地址
        oss = new OSSClient(getApplicationContext(), Contents.ENDPOINT, credentialProvider, conf);
    }

    private void setUi() {
        name_textview.setText(spImp.getNick());
        sex_textview.setText(spImp.getSex() == 0 ? "男" : "女");

        if (!AppUtils.isEmpty(spImp.getBirthday())) {
            String birthday = "";
            birthday = year + "年";
            if (month < 10) {
                birthday = birthday + "0";
            }
            birthday = birthday + month + "月";
            if (day < 10) {
                birthday = birthday + "0";
            }
            birthday = birthday + day + "日";
            birthday_textview.setText(birthday);
        }
        introduction_textview.setText(spImp.getIntroduction());
    }

    //用户信息修改(改)
    private void editUserInfo() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        map.put("nick", nick);
        map.put("sex", sex + "");
        map.put("birthday", year + "-" + month + "-" + day);
        map.put("headUrl", headUrl);
        map.put("introduction", introduction);

        MyOkHttpUtils.getServiceDatas(map, Contents.ACCOUNT_EDITUSERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        spImp.setHeadUrl(headUrl);
                        spImp.setNick(nick);
                        spImp.setSex(sex);
                        spImp.setBirthday(year + "-" + month + "-" + day);
                        spImp.setIntroduction(introduction);
                        setUi();
                        if (isUrlChanging) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    glideUtils.showCircle(spImp.getHeadUrl(), head_imageview);
                                    isUrlChanging = false;
                                }
                            }, 1000);
                        }
                        ToastUtils.showToast("修改成功");
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //初始化图库
    private void initGallery() {

        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Loger.e("initGallery", "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Loger.e("initGallery", "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Loger.e("initGallery", s);
                    path.add(s);
                }
                for (int i = 0; i < path.size(); i++) {
                    Loger.e("path：", path.get(i));
                }
                ossUpload(path.get(0));
            }

            @Override
            public void onCancel() {
                Loger.e("initGallery", "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Loger.e("initGallery", "onFinish: 结束");
            }

            @Override
            public void onError() {
                Loger.e("initGallery", "onError: 出错");
            }
        };

        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.shxc.smarttrade.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 1)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(1)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 512, 512)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                .filePath("/SmartTrade/Pictures")          // 图片存放路径
                .build();
    }

    // 授权管理 - 相册
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(mContext, "请在 setting-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
        }
    }

    // 授权管理 - 相机
    private void initPermissions2() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
                return;
            } else {
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
        }
    }

    // 授权返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Loger.e("initPermissions", "同意授权");
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
                } else {
                    Loger.e("initPermissions", "拒绝授权");
                }
                break;
            case PERMISSIONS_REQUEST_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(this);
                } else {
                    // Permission Denied
                    Toast.makeText(this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //OSS上传
    public void ossUpload(String strPath) {
        loadingDialog.show();
        isUrlChanging = true;
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(ContentsSwitch.BUCKET_NAME, Contents.USER_IMG_URL + "user_head_" + spImp.getInviteCode() + "_big.jpg", strPath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Loger.e("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Loger.e("PutObject", "UploadSuccess");
                Loger.e("headUrl", "http://" + ContentsSwitch.BUCKET_NAME + "." + Contents.ENDPOINT + "/" + Contents.USER_IMG_URL + "user_head_" + spImp.getInviteCode() + "_big.jpg");
                headUrl = "http://" + ContentsSwitch.BUCKET_NAME + "." + Contents.ENDPOINT + "/" + Contents.USER_IMG_URL + "user_head_" + spImp.getInviteCode() + "_big.jpg";
                editUserInfo();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    Loger.e("xx", "xxx");
                }
                if (serviceException != null) {
                    // 服务异常
                    Loger.e("ErrorCode", serviceException.getErrorCode());
                    Loger.e("RequestId", serviceException.getRequestId());
                    Loger.e("HostId", serviceException.getHostId());
                    Loger.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待直到任务完成
    }


}
